const admin = require("../dao/adminDao");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const err = require("../utils/errors");

//登录
const loginService = async (info) => {
  info.loginPwd = md5(info.loginPwd);
  const result = await admin.login(info);
  if (result && result.dataValues) {
    const { remember = 1 } = info;
    //添加token
    const token = jwt.sign(result.dataValues, md5(process.env.JWT_SECRYT), {
      expiresIn: 60 * 60 * 24 * remember,
      algorithm: "HS256",
    });
    return {
      data: result.toJSON(),
      token,
    };
  }
  return { data: result };
};

//修改
const updateService = async (info) => {
  const user = await admin.login({
    loginId: info.loginId,
    loginPwd: md5(info.oldLoginPwd),
  });
  //查找用户是否存在
  if (user && user.dataValues) {
    await admin.update({
      name: info.name,
      loginId: info.loginId,
      loginPwd: md5(info.loginPwd),
      oldLoginPwd: md5(info.oldLoginPwd),
    });
    return {
      loginId: info.loginId,
      name: info.name,
      id: user.dataValues.id,
    };
  } else {
    throw new err.ValidationError("用户不存在或旧密码错误");
  }
};

module.exports = {
  loginService,
  updateService,
};
